package com.ylkj.wx.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.lang3.StringUtils;
import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ylkj.wx.constant.ErrorType;
import com.ylkj.wx.constant.WeiXBaseConstant;
import com.ylkj.wx.constant.WeiXConstant;
import com.ylkj.wx.dto.UnifiedOrderDto;
import com.ylkj.wx.entitis.WXPicInfo;
import com.ylkj.wx.entitis.WeixUserBasicInfo;
import com.ylkj.wx.exception.WeichatException;
import com.ylkj.wx.message.req.QRCodePermanent;
import com.ylkj.wx.message.req.QRCodeScene;
import com.ylkj.wx.message.req.QRCodeSceneStr;

public class WeixCommonUtil {    
    private static final Logger LOGGER = LoggerFactory.getLogger(WeixCommonUtil.class);
	/**
	    * 获得ACCESS_TOKEN 请慎用该函数，有使用次数限制，建议通过缓存取得
	    * @param @return 设定文件
	    * @return String 返回类型
	    * @throws IOException, WeichatException
	    */
	public static String getAccessToken() throws IOException, WeichatException {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
		url = String.format(url, WeiXBaseConstant.WEICHAT_APPID,
				WeiXBaseConstant.WEICHAT_SECRET);
		String accessToken = "";
		String content = HttpUtils.getContentByGet(url);
        JSONObject jsonObject = JSONObject.parseObject(content);
        //解析微信状态码
        parseStatus(jsonObject);
        accessToken = jsonObject.getString("access_token");
        String expiresIn = jsonObject.getString("expires_in");
        LOGGER.info("getAccessToken  accessToken = " + accessToken + "   expiresIn = " + expiresIn);
		return accessToken;
	}
	
	/**
	    * 获得JsapiTicket 请慎用该函数，有使用次数限制，建议通过缓存取得
	    * @param @return 设定文件
	    * @return String 返回类型
	    * @throws IOException, WeichatException
	    */
	public static String getJsapiTicket(String accessToken) throws IOException,
			WeichatException {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
		url = String.format(url, accessToken);
		String content = HttpUtils.getContentByGet(url);
		JSONObject jsonObject = JSONObject.parseObject(content);
		// 解析微信状态码
		parseStatus(jsonObject);
		String jsapiTicket = jsonObject.getString("ticket");

		return jsapiTicket;
	}
	
	/**
	    * 获取微信用户基本信息
	    * @param openId
	    * @return String 返回类型
	    * @throws IOException, WeichatException
	    */
	public static WeixUserBasicInfo getWeixUserBasicInfo(String openId, String accessToken) throws IOException, WeichatException {
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
		url = String.format(url, accessToken, openId);
		String content = HttpUtils.getContentByGet(url);
	    JSONObject jsonObject = JSONObject.parseObject(content);
	    //解析微信状态码
	    parseStatus(jsonObject);
	    Gson gson = new Gson();
	    WeixUserBasicInfo weixUserBasicInfo = gson.fromJson(content, WeixUserBasicInfo.class);
		return weixUserBasicInfo;
	}
	
	/**
	    * 获取微信用户基本信息
	    * @param openId
	    * @return String 返回类型
	    * @throws IOException, WeichatException
	    */
	public static String getWeixUserBasicInfoTest(String openId, String accessToken) throws IOException, WeichatException {
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
		url = String.format(url, accessToken, openId);
		String content = HttpUtils.getContentByGet(url);
	    JSONObject jsonObject = JSONObject.parseObject(content);
	    //解析微信状态码
	    parseStatus(jsonObject);
	    Gson gson = new Gson();
	    WeixUserBasicInfo weixUserBasicInfo = gson.fromJson(content, WeixUserBasicInfo.class);
	    System.out.println(weixUserBasicInfo.getNickname());
	    System.out.println(weixUserBasicInfo.getCountry());
		return content;
	}
	
    /**
     * 
     * 调用微信API后,解析微信返回的状态消息。
     * 
     * @param returnContent 微信返回的信息
     * @throws WeichatException void
     */
    private static void parseStatus(JSONObject returnContent) throws WeichatException {
        String errorCode = returnContent.getString("errcode");
        if(StringUtils.isNotBlank(errorCode) && !StringUtils.equalsIgnoreCase(errorCode, "0")){
            LOGGER.info("errorCode:"+errorCode);
            throw new WeichatException(ErrorType.obtainMessage(errorCode));
        }
    }
    
    /**
     * 获取媒体文件
     * @param accessToken 接口访问凭证
     * @param media_id 媒体文件id
     * @throws Exception 
     * */
	public static WXPicInfo downloadMedia(String accessToken, String mediaId) throws Exception {
		byte[] buffer = null; 
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
		requestUrl = String.format(requestUrl, accessToken, mediaId);
		
		URL url = new URL(requestUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		// 根据内容类型获取扩展名
		String fileExt = conn.getHeaderField("Content-Type");
		if(fileExt.indexOf("/") != -1){
			fileExt = fileExt.substring(fileExt.indexOf("/")+1);
		}
		// 将mediaId作为文件名
		BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
		byte[] buf = new byte[8096];
		int size = 0;
		while ((size = bis.read(buf)) != -1) {
			bos.write(buf, 0, size);
		}
		bis.close();
		bos.close();
		conn.disconnect();
		buffer = bos.toByteArray();
		
		WXPicInfo picInfo = new WXPicInfo();
		picInfo.setFileExt(fileExt);
		picInfo.setMediaData(buffer);
		return picInfo;
	}
	
	/**
	 * 
	 * <p>上传多媒体文件</p>
	 * @param accessToken
	 * @param fileType
	 * @param filePath
	 * @return
	 * @throws Exception String
	 * @since   1.0.0
	 */
	public static String uploadMedia(String accessToken, String fileType,
			String filePath) throws Exception {
		String result = null;
		InputStream iputstream = null;
		BufferedReader reader = null;
		DataInputStream in = null;
		OutputStream out = null;
		try {
		    String[] urlname = filePath.split("/");   
		    int len = urlname.length-1;   
		    String fileName = urlname[len];//获取文件名  
			URL url = new URL(filePath);   
	        HttpURLConnection uc = (HttpURLConnection) url.openConnection(); 
	        uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true   
	        uc.connect();   
	        iputstream = uc.getInputStream();
			
			String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s";
			requestUrl = String.format(requestUrl, accessToken, fileType);
			URL urlObj = new URL(requestUrl);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
			con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// 设置边界
			String boundary = "----------" + System.currentTimeMillis();
			con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
					+ boundary);
	
			// 请求正文信息
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // 必须多两道线
			sb.append(boundary);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
					+ fileName + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] head = sb.toString().getBytes("utf-8");
			// 获得输出流
			out = new DataOutputStream(con.getOutputStream());
			// 输出表头
			out.write(head);
			// 文件正文部分
			// 把文件已流文件的方式 推入到url中
			in = new DataInputStream(iputstream);
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			// 结尾部分
			byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			StringBuffer buffer = new StringBuffer();
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));

			String line = null;

			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			throw new IOException("数据读取异常");
		} finally {
			if (reader != null) {
				reader.close();
			}
			if(in != null){
				in.close();
			}
			if(out != null){
				out.close();
			}
			if(iputstream != null){
				iputstream.close();
			}
		}
		JSONObject jsonObject = JSONObject.parseObject(result);
		String mediaId = jsonObject.getString("media_id");
		return mediaId;
	}
	
	/**
	    * 获得永久二维码的ticket 
 	    * @param accessToken
 	    * @param doctorCode 
 	    * 
	    * @return String 永久二维码的ticket 
	    * @throws IOException, WeichatException
	    * @throws InterruptedException 
	    * @throws ExecutionException 
	    */
	public static String getQRCodeTicket(String accessToken, String doctorCode) throws Exception {
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";
		url = String.format(url, accessToken);
		//设置请求永久二维码的参数
		QRCodePermanent qrCodePermanent = new QRCodePermanent();
		qrCodePermanent.setAction_name("QR_LIMIT_STR_SCENE");
		QRCodeScene qrCodeScene = new QRCodeScene();
		QRCodeSceneStr qrCodeSceneStr = new QRCodeSceneStr();
		qrCodeSceneStr.setScene_str(doctorCode);
		qrCodeScene.setScene(qrCodeSceneStr);
		qrCodePermanent.setAction_info(qrCodeScene);
		Gson gson = new Gson();
		String parm = gson.toJson(qrCodePermanent);
		String content = HttpUtils.post(url, parm);
		JSONObject jsonObject = JSONObject.parseObject(content);
		// 解析微信状态码
		parseStatus(jsonObject);
		String qrCodeTicket = jsonObject.getString("ticket");
		return qrCodeTicket;
	}
	
	/**
	    * 根据永久二维码的ticket获得二维码图片的字节流 
	    * @param qrCodeTicket
	    * 
	    * @return WXPicInfo 二维码图片的字节流 与扩展名
	    * @throws IOException, WeichatException
	    * @throws InterruptedException 
	    * @throws ExecutionException 
	    */
	public static WXPicInfo getQRCodeBytes(String qrCodeTicket) throws Exception {
		byte[] buffer = null; 
		// 拼接请求地址
		String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
		requestUrl = String.format(requestUrl, qrCodeTicket);
		
		URL url = new URL(requestUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		
		// 根据内容类型获取扩展名
		String fileExt = conn.getHeaderField("Content-Type");
		if(fileExt.indexOf("/") != -1){
			fileExt = fileExt.substring(fileExt.indexOf("/")+1);
		}

		BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
		byte[] buf = new byte[1024];
		int size = 0;
		while ((size = bis.read(buf)) != -1) {
			bos.write(buf, 0, size);
		}
		bis.close();
		bos.close();
		conn.disconnect();
		buffer = bos.toByteArray();
		
		WXPicInfo picInfo = new WXPicInfo();
		picInfo.setFileExt(fileExt);
		picInfo.setMediaData(buffer);
		return picInfo;
	}
	
	
	/**
	 * 
	 * <p>上传多媒体文件 </p>
	 * @param accessToken
	 * @param wXMessageDTO
	 * @return
	 * @throws Exception boolean
	 * @since   1.0.0
	 */
/*	public static boolean pushMessageToWX(String accessToken, WXMessageDTO wXMessageDTO) throws Exception {
		boolean pushResult = false;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";
		requestUrl = String.format(requestUrl, accessToken);
		
		//设置请求永久二维码的参数
		Gson gson = new Gson();
		String parm = gson.toJson(wXMessageDTO);
		String content = HttpUtils.post(requestUrl, parm);
		JSONObject jsonObject = JSONObject.parseObject(content);
		// 解析微信状态码
		parseStatus(jsonObject);
		pushResult = true;
		return pushResult;
	}*/
	
	/**
     * 
     * 根据作用域的Scope snsapi_base 获取用户openId
     * 
     * @param code
     * @return WechatUserInfo
     * @throws IOException 
     * @throws HttpException 
     * @throws WeichatException 
     */
    public static String obtainOpenId(String code) throws IOException, WeichatException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url, WeiXBaseConstant.WEICHAT_APPID,WeiXBaseConstant.WEICHAT_SECRET, code);
        LOGGER.info("Obtain openid & access_token by weichat interface :" + url);
        String content = HttpUtils.getContentByGet(url);
        JSONObject jsonObject = JSONObject.parseObject(content);
        //解析微信状态码
        parseStatus(jsonObject);
        String openId = jsonObject.getString("openid");
        return openId;
    }
	
	/**
	 * 
	 * <p>推送客服消息给用户，如果由于推送失败（45047）则返回false </p>
	 * @param accessToken
	 * @param wXMessageDTO
	 * @return
	 * @throws Exception boolean
	 * @since   1.0.0
	 */
	public static boolean pushMessageToUser(String accessToken, String parm) throws Exception {
		boolean pushResult = false;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";
		requestUrl = String.format(requestUrl, accessToken);
		
		//设置请求永久二维码的参数
		String content = HttpUtils.post(requestUrl, parm);
		JSONObject jsonObject = JSONObject.parseObject(content);
		// 解析微信状态码
        String errorCode = jsonObject.getString("errcode");
        if(StringUtils.isNotBlank(errorCode) && !StringUtils.equalsIgnoreCase(errorCode, "0")){
        	//客服接口下行条数超过上限或 回复时间超过限制
        	if(!"45047".equals(errorCode) && !"45015".equals(errorCode)){
                LOGGER.info("errorCode:"+errorCode);
                throw new WeichatException(ErrorType.obtainMessage(errorCode));
        	}
        }else{
    		pushResult = true;
        }

		return pushResult;
	}
	
	   /**
     * 微信头像二进制流
     * @param headUrl 微信头像url
     * @throws Exception 
     * */
	public static byte[] downloadHeadUrl(String headUrl) throws Exception {
		byte[] buffer = null; 
		
		URL url = new URL(headUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		// 根据内容类型获取扩展名
		String fileExt = conn.getHeaderField("Content-Type");
		if(fileExt.indexOf("/") != -1){
			fileExt = fileExt.substring(fileExt.indexOf("/")+1);
		}
		// 将mediaId作为文件名
		BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
		byte[] buf = new byte[8096];
		int size = 0;
		while ((size = bis.read(buf)) != -1) {
			bos.write(buf, 0, size);
		}
		bis.close();
		bos.close();
		conn.disconnect();
		buffer = bos.toByteArray();
		
		
		return buffer;
	}
	
	/**
	 * 
	 * <p>上传多媒体文件 </p>
	 * @param accessToken
	 * @param wXMessageDTO
	 * @return
	 * @throws Exception boolean
	 * @since   1.0.0
	 */
	public static boolean pushTemplateMessageToUser(String accessToken, String parm) throws Exception {
		boolean pushResult = false;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
		requestUrl = String.format(requestUrl, accessToken);
		
		//设置请求永久二维码的参数
		String content = HttpUtils.post(requestUrl, parm);
		JSONObject jsonObject = JSONObject.parseObject(content);
		// 解析微信状态码
		parseStatus(jsonObject);
		pushResult = true;
		return pushResult;
	}
	
	public static UnifiedOrderDto queryUnifiedOrder(UnifiedOrderDto unifiedorder) {
		SortedMap<Object, Object> param = unifiedorderParam(unifiedorder);
		String requestXML = XMLUtil.getReqXml(param);
		// 调用统一接口
		String result = HttpUtils.sendPost(WeiXConstant.pay_queryorder_url, requestXML);
		try {
			Map<String, String> unifiedPayMap = XMLUtil.doXMLParse(result);
			if ("SUCCESS".equals(unifiedPayMap.get("result_code"))) {
				String openid = unifiedPayMap.get("openid");
				String transaction_id = unifiedPayMap.get("transaction_id");
				String out_trade_no = unifiedPayMap.get("out_trade_no");
				
			}
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return unifiedorder;
	}
	
	public static UnifiedOrderDto unifiedOrder(UnifiedOrderDto unifiedorder) {
		// TODO Auto-generated method stub
		SortedMap<Object, Object> param = unifiedorderParam(unifiedorder);
		String requestXML = XMLUtil.getReqXml(param);
		System.out.println("---requestXML-----------------------"+requestXML);
		// 调用统一接口
		String unifiedPayResult = HttpUtils.sendPost(WeiXConstant.pay_unifiedorder_url, requestXML);
		System.out.println("---unifiedPayResult-----------------------"+unifiedPayResult);
		try {
			unifiedPayResult = new String(unifiedPayResult.getBytes(),"utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		System.out.println("---unifiedPayResult-----------------------"+unifiedPayResult);
		try {
			Map<String, String> unifiedPayMap = XMLUtil.doXMLParse(unifiedPayResult);
			System.out.println("---result_code---------------------------"+unifiedPayMap.get("result_code"));
			System.out.println("---return_msg---------------------------"+unifiedPayMap.get("return_msg"));
			System.out.println("---return_code---------------------------"+unifiedPayMap.get("return_code"));
			if ("SUCCESS".equals(unifiedPayMap.get("result_code"))) {
				String mweb_url = unifiedPayMap.get("mweb_url");
				unifiedorder.setMwebUrl(mweb_url);
				/*	long timestamp = new Date().getTime();
				String signature = "";
				try {
					String jsurl = WeiXConstant.domain_url+ "/wx/page/index/";
					signature = getSignature(timestamp, unifiedorder.getNonceStr(),jsurl);
					signature = "";
				} catch (Exception e) {
					LOGGER.error("获取数字签名失败。");
				}
				unifiedorder.setSignature(signature);
				unifiedorder.setTimeStamp(Long.toString(timestamp));
				unifiedorder.setPackageValue("prepay_id="+ unifiedPayMap.get("prepay_id"));
				unifiedorder.setSignType(WeiXBaseConstant.SIGN_TYPE);
				
				SortedMap<Object, Object> signPay = paySign(unifiedorder);
				
				unifiedorder.setPaySign(StringUtils.defaultString(String
						.valueOf(signPay.get("sign"))));
				
				String action = "%2Fhygea%2Fwebapp%2FstoreHome%23%2FgroupPaySuccess%3ForderNo%3D"
						+ unifiedorder.getOutTradeNo();

				unifiedorder.setPaySucessUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf9ce31f104231fe0&redirect_uri="
								+ WeiXConstant.domain_url
								+ action
								+ "&response_type=code&scope=snsapi_base&state=order&connect_redirect=1#wechat_redirect");*/

			}
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return unifiedorder;
	}
	

	public static String getJsapiTicket() {
		String jsapiTicket = "";
/*		try {
			// 从redis中获得Access_Token，和AccessExpires
			AccessTokenEntity jsapiTicketEntity = CacheHelper.getObject(WeiXBaseConstant.JSAPI_TICKET_KEY, AccessTokenEntity.class);
			if (jsapiTicketEntity != null) {
				jsapiTicket = jsapiTicketEntity.getAccessToken();
			}
		} catch (Exception e) {
			LOGGER.error("jsapiTicket读取失败！", e);
		}
		LOGGER.info("jsapiTicket is ===" + jsapiTicket);*/
		return jsapiTicket;
	}

	/* (non-Javadoc)
	 * @see com.xikang.ch.cloudweix.facade.WXInfoFacade#getSignature()
	 */

	public static String getSignature(long timestamp, String nonce, String jsurl) throws NoSuchAlgorithmException {
		String jsapiTicket = getJsapiTicket();
		LOGGER.info(jsapiTicket +" === "+ timestamp+" === " + nonce+" === " + jsurl);
		String signature = ShaUtil.getJsapiTicket(jsapiTicket, timestamp, nonce, jsurl);
		LOGGER.info("signature is ===" + signature);
		return signature;
	}
	/**
	 * 调用统一接口参数
	 * 
	 * @param unifiedorderDTO
	 * @return
	 */
	private static SortedMap<Object, Object> unifiedorderParam(UnifiedOrderDto unifiedorderDTO) {
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", unifiedorderDTO.getAppId()); // 服务号Appid
		parameters.put("body", unifiedorderDTO.getBody()); // 商品或支付单简要描述
		
		parameters.put("mch_id", unifiedorderDTO.getMchId()); // 商户号ID
		parameters.put("nonce_str", unifiedorderDTO.getNonceStr());// 随机数 32位随机码
		parameters.put("notify_url", unifiedorderDTO.getNotifyUrl());// 回调URL
																	// 商品描述
		parameters.put("out_trade_no", unifiedorderDTO.getOutTradeNo()); // 订单号
		parameters.put("spbill_create_ip", unifiedorderDTO.getSpbillCreateIp());// APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP，用户端的ID
																	// 商户系统内部的订单号,32个字符内、可包含字母
		parameters.put("total_fee", unifiedorderDTO.getTotalFee());// 订单总金额，只能为整数
		parameters.put("trade_type", unifiedorderDTO.getTradeType());// 支付类型
		parameters.put("scene_info", unifiedorderDTO.getSceneInfo());// 场景信息
		//parameters.put("openid", unifiedorderDTO.getOpenid());// 授权ID
		String sign = SignUtil.createSign("UTF-8", parameters);
		parameters.put("sign", sign); // 签名
		return parameters;
	}

	/**
	 * 生成支付 sign
	 * 
	 * @param unifiedorderDTO
	 * @return
	 */
	private static SortedMap<Object, Object> paySign(UnifiedOrderDto unifiedorderDTO) {
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appId", unifiedorderDTO.getAppId()); // 服务号Appid
		parameters.put("timeStamp", unifiedorderDTO.getTimeStamp());
		parameters.put("nonceStr", unifiedorderDTO.getNonceStr());
		parameters.put("package", unifiedorderDTO.getPackageValue());
		parameters.put("signType", unifiedorderDTO.getSignType());
		String sign = SignUtil.createSign("UTF-8", parameters);
		parameters.put("sign", sign); // 签名
		return parameters;
	}
}
